import axios from 'axios'
import qs from 'qs'

axios.defaults.baseURL = 'http://localhost'

const URLS = {
    types:'/filmApi/loadTypes.php',
    films:'/filmApi/loadFilms.php',
    filmById:'/filmApi/loadFilmById.php',
    comments:'/filmApi/loadComments.php',
    addComment:'/filmApi/addComment.php'

}

const loadTypes = () => {
    // 返回Promise对象
    return axios.get(URLS.types)
        .then(res => {
            if(res.data.resultState){
                return res.data.result
            }
            return Promise.reject({
                message:res.data.message
            })
        })
}

const loadFilmsByParams = params => {
    return axios.post(URLS.films,qs.stringify(params))
        .then(res => {
            if(res.data.resultState){
                return res.data.result
            }
            return Promise.reject({
                message:res.data.message
            })
        })
}

const loadFilmByFilmId = params => {
    return axios.post(URLS.filmById,qs.stringify(params))
        .then(res => {
            if(res.data.resultState){
                return res.data.result
            }
            return Promise.reject({
                message:res.data.message
            })
        })
}

const loadCommentsByFilmId = params => {
    return axios.post(URLS.comments,qs.stringify(params))
        .then(res => {
            if(res.data.resultState){
                return res.data.result
            }
            return Promise.reject({
                message:res.data.message
            })
        })
}

const addComment = params => {
    return axios.post(URLS.addComment,qs.stringify(params))
        .then(res => {
            if(res.data.resultState){
                return res.data.message
            }
            return Promise.reject({
                message:res.data.message
            })
        })
}

export default {
    install(Vue){
        Vue.prototype.$api = {
            loadTypes,
            loadFilmsByParams,
            loadFilmByFilmId,
            loadCommentsByFilmId,
            addComment
        }
    }
}